package com.wjh.anyview.websocket.config;

import com.wjh.anyview.websocket.server.StudentLoginServer;
import com.wjh.anyview.websocket.server.TeacherLoginServer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * redis消息对象的监听者配置类
 *
 * @author wjh
 * @date 2021/10/11 21:06
 * @Package com.example.demo.config
 */
@Configuration
@AutoConfigureAfter({MessageListenerAdapter.class})
public class SubscriberConfig {
    /**
     * 消息监听适配器，注入接受消息方法，输入方法名字 反射方法
     *
     * @param studentLoginServer 频道监听者--登录服务
     * @return MessageListenerAdapter对象
     */
    @Bean
    public MessageListenerAdapter messageListenerAdapter(StudentLoginServer studentLoginServer) {
        return new MessageListenerAdapter(studentLoginServer, "getRedisMessage");
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter2(TeacherLoginServer teacherLoginServer) {
        return new MessageListenerAdapter(teacherLoginServer, "getRedisMessage");
    }

    /**
     * 创建消息监听容器（用于监听TOPIC_USERNAME）
     *
     * @param redisConnectionFactory RedisConnectionFactory
     * @param messageListenerAdapter MessageListenerAdapter
     * @return redisMessageListenerContainer
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter messageListenerAdapter, MessageListenerAdapter messageListenerAdapter2) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        //监听 TOPIC_USERNAME 频道
        PatternTopic topicUsername = new PatternTopic("TOPIC_USERNAME");
        //监听 TOPIC_PRE_EXAM 频道
        PatternTopic topicPreExam = new PatternTopic("TOPIC_EXAM");
        //监听 TOPIC_TEACHER 频道
        PatternTopic topicTeacher = new PatternTopic("TOPIC_TEACHER");
        container.addMessageListener(messageListenerAdapter, topicUsername);
        container.addMessageListener(messageListenerAdapter, topicPreExam);
        container.addMessageListener(messageListenerAdapter2, topicTeacher);
        return container;
    }
}